<?php
/**
 * Created by IntelliJ IDEA.
 * User: ahwwl
 * Date: 2018/1/29
 * Time: 下午4:33
 */

namespace app\controller;


use app\model\AgentList;
use app\model\CardList;
use app\model\OrderList;
use app\model\TransfersList;
use app\model\UserCardList;
use app\model\UserList;
use app\model\WalletLog;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\Request;

/**
 * @property AgentList AgentList
 * @property UserList UserList
 * @property UserCardList UserCardList
 * @property CardList CardList
 * @property TransfersList TransfersList
 * @property WalletLog WalletLog
 * @property OrderList OrderList
 */
class Agents extends CommonController
{
    function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->AgentList = new AgentList();
        $this->UserList = new UserList();
        $this->UserCardList = new UserCardList();
        $this->CardList = new CardList();
        $this->TransfersList = new TransfersList();
        $this->WalletLog = new WalletLog();
        $this->OrderList = new OrderList();
    }
    function agent_list()
    {

        $this->assign("page_title","代理列表");
        return $this->fetch();
    }
    function ajax_agent_list()
    {
        try
        {
            $page = input("page",1,"intval");
            $rows = input("rows",30,"intval");
            $mobile = input("mobile","","trim");
            $agent_name = input("agent_name","","trim");

            $where = [];
            if(!empty($mobile))
                $where["mobile"] = $mobile;
            if(!empty($agent_name))
                $where["agent_name"] = ["like","%".$agent_name."%"];

            $count = $this->AgentList
                ->where($where)
                ->count();
            $page_total = ceil($count/$rows);
            $page = $page>$page_total?$page_total:$page;
            $page = $page < 1? 1:$page;
            $order_log = $this->AgentList
                ->where($where)
                ->order("id desc")
                ->limit(($page-1)*$rows,$rows)
                ->select();
            $this->resultdata["data"] = $order_log;
            $this->resultdata["error"] = 0;
            $this->resultdata["total"] = $count;
            $this->resultdata["page"] = $page;
            $this->resultdata["rows"] = $rows;
        }catch (\Exception $e)
        {

            $this->resultdata["msg"] = $e->getMessage();
        }
        echo json_encode($this->resultdata);
    }
    function ajax_agent_info()
    {
        try
        {
            $id = input("id",0,"intval");
            if(empty($id))
                $this->E("参数不能为空");
            $info = $this->AgentList->where(["id"=>$id])->find();
            $info["card_fee"] =number_format($info["card_fee"]/10000, 2, '.', '');
            $info["freight"] =number_format($info["freight"]/10000, 2, '.', '');
            $this->resultdata["data"] = $info;
            $this->resultdata["error"] = 0;
        }catch (\Exception $e)
        {
            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }
    function ajax_agent_info_save()
    {
        try
        {
            $id = input("id",0,"intval");
            $agent_name = input("agent_name","","trim");
            $agent_info = input("agent_info","","trim");
            $agent_type = input("agent_type",0,"intval");
            $card_fee = input("card_fee",0,"intval");
            $freight = input("freight",0,"intval");
            $money_discount = input("money_discount",0.00,"floatval");
            $rebate_discount = input("rebate_discount",0.00,"floatval");
            $money_discount_0 = input("money_discount_0",0.00,"floatval");
            $rebate_discount_0 = input("rebate_discount_0",0.00,"floatval");
            $sign_key = input("sign_key","","trim");

            $status = input("status",0,"intval");
            if(!in_array($status,[0,1])||!in_array($agent_type,[0,1])||empty($agent_name))
                $this->E("参数不正确");
            $card_fee = $card_fee*10000;
            $freight = $freight*10000;
            $info = [
                "agent_name"=>$agent_name,
                "agent_info"=>$agent_info,
                "agent_type"=>$agent_type,
                "card_fee"=>$card_fee,
                "freight"=>$freight,
                "money_discount"=>$money_discount,
                "rebate_discount"=>$rebate_discount,
                "money_discount_0"=>$money_discount_0,
                "rebate_discount_0"=>$rebate_discount_0,
                "sign_key"=>$sign_key,
                "status"=>$status
            ];
            if($id)
            {
                $query = $this->AgentList->where(["id"=>$id])->update($info);
                if(empty($query))
                {
                    $this->E("更新失败");
                }
            }else{
                $id = $this->AgentList->insertGetId($info);
                if(empty($id))
                {
                    $this->E("添加失败");
                }
            }
            $this->resultdata["error"] = 0;
        }catch (\Exception $e)
        {
            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }
    function ajax_agent_set_credit()
    {
        try
        {
            $id = input("id",0,"intval");
            $credit = input("credit",0,"intval");
            if(empty($id)||empty($credit))
                $this->E("参数不正确");
            $credit = $credit*10000;
            $query = $this->AgentList->where(["id"=>$id])->setInc("credit",$credit);
            if(empty($query))
            {
                $this->E("更新失败");
            }
            $this->resultdata["error"] = 0;
        }catch (\Exception $e)
        {
            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }
    function ajax_agent_set_balance()
    {
        try
        {
            $id = input("id",0,"intval");
            $balance = input("balance",0,"intval");
            if(empty($id)||empty($balance))
                $this->E("参数不正确");
            $balance = $balance*10000;

            Db::startTrans();
            try{
                $query = $this->AgentList->where(["id"=>$id])->setInc("balance",$balance);
                if(empty($query))
                {
                    $this->E("更新失败");
                }
                $wallet_info = [
                    "agent_id"=>$id,
                    "type"=>3,
                    "money"=>$balance,
                    "info"=>"代理加款：".($balance/10000),
                    "ctime"=>NOW_TIME

                ];
                $query = $this->WalletLog->insert($wallet_info);
                if(empty($query))
                {

                    $this->E("流水添加失败");
                }
                Db::commit();
            }catch (\Exception $e)
            {
                Db::rollback();
                $this->E($e->getMessage());
            }
            $this->resultdata["error"] = 0;
        }catch (\Exception $e)
        {
            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }
    function agent_card_list()
    {
        try {
            $user_ids = $this->UserList->field("id,real_name,mobile")->select();
            $agent_card_list = $this->CardList->where(["status"=>0])->select();
            $agent_list = $this->AgentList->where(["status"=>0])->select();
            $this->assign("agent_card_list",$agent_card_list);
            $this->assign("user_ids",$user_ids);
            $this->assign("agent_list",$agent_list);
        } catch (DataNotFoundException $e) {
        } catch (ModelNotFoundException $e) {
        } catch (DbException $e) {
        }

        $this->assign("page_title","代理卡列表");
        return $this->fetch();
    }
    function ajax_agent_card_list()
    {
        try
        {
            $page = input("page",1,"intval");
            $rows = input("rows",30,"intval");
            $mobile = input("mobile","","trim");
            $real_name = input("real_name","","trim");
            $agent_id = input("agent_id",0,"intval");
            $card_no = input("card_no","","trim");

            $where = [];
            if(!empty($mobile))
                $where["b.mobile"] = $mobile;
            if(!empty($real_name))
                $where["b.real_name"] = ["like",$real_name."%"];
            if(!empty($agent_id))
                $where["a.agent_id"] =$agent_id;
            else
                $where["a.agent_id"] = ["gt",0];
            if(!empty($card_no))
                $where["a.card_no"] = ["like","%".$card_no."%"];

            $count = $this->UserCardList->alias("a")
                ->join("f_user_list b","a.user_id=b.id","left")
                ->where($where)
                ->count();
            $page_total = ceil($count/$rows);
            $page = $page>$page_total?$page_total:$page;
            $page = $page < 1? 1:$page;
            $order_log = $this->UserCardList->alias("a")
                ->join("f_user_list b","a.user_id=b.id","left")
                ->join("f_agent_list al" ,"al.id=a.agent_id","left")
                ->field("a.*,b.real_name,b.mobile,al.agent_name")
                ->where($where)
                ->order("a.id desc")
                ->limit(($page-1)*$rows,$rows)
                ->select();
            $user_card_idle_list = $this->UserCardList->where(["user_id"=>0,"card_type"=>["GT",0]])->select();
            $this->resultdata["user_card_idle_list"] = $user_card_idle_list;
            $this->resultdata["data"] = $order_log;
            $this->resultdata["error"] = 0;
            $this->resultdata["total"] = $count;
            $this->resultdata["page"] = $page;
            $this->resultdata["rows"] = $rows;
        }catch (\Exception $e)
        {

            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }
    function ajax_agent_card_add()
    {
        try
        {
            $agent_id = input("agent_id",0,"intval");
            $card_no = input("card_no","","trim");
            $card_fee = input("card_fee",0,"intval");
            $freight = input("freight",0,"intval");

            if(empty($agent_id)||empty($card_no))
                $this->E("参数不正确");
            $card_fee = $card_fee*10000;
            $freight = $freight*10000;
            $info = [
                "agent_id"=>$agent_id,
                "card_no"=>$card_no,
                "card_fee"=>$card_fee,
                "status"=>1,
                "ctime" =>NOW_TIME
            ];
            $CardInfo = $this->CardList->where(["card_no"=>$card_no])->find();
            if(empty($CardInfo))
            {
                $this->E("此卡不在库中");
            }
            $card_type = $CardInfo["card_type"];
            $info["card_type"] = $card_type;
            $basic_price = intval($CardInfo["balance"]);
//            $agent_rebate = floatval($this->config_list["AGENT_REBATE"]["value"]);
            $agent_discount = floatval($this->config_list["AGENT_DISCOUNT"]["value"]);
            $cost_discount = floatval($this->config_list["CARD_1_COST_DISCOUNT"]["value"]);
            $money = $basic_price*$agent_discount;
            $cost = $basic_price*$cost_discount/100;
            $total_money = $money+$card_fee+$freight;
            if($CardInfo["status"]!=0)
                $this->E("此卡禁用或使用中");
            $user_card_info =$this->UserCardList->where(["card_no"=>$card_no])->find();
            if(!empty($user_card_info))
            {
                if($user_card_info["agent_id"] == $agent_id)
                {
                    $this->E("此卡已经绑定");
                }else{
                    $this->E("此卡已经被别的代理绑定，解绑后可绑定");
                }
            }
            Db::startTrans();
            try{
                $query = $this->AgentList->where(["id"=>$agent_id])->where("(balance+credit)>=".$total_money)->setDec("balance",$total_money);
                if(empty($query))
                {
                    $this->E("余额不足");
                }

                $id = $this->UserCardList->insertGetId($info);
                if(empty($id))
                {
                    $this->E("添加失败");
                }
                $query = $this->CardList->where(["status"=>0,"card_no"=>$card_no])->update(["status"=>1]);
                if(empty($query))
                {
                    $this->E("添加失败");
                }
                $ip = $this->request->ip();
                $order_info = $this->OrderList->addAgentCardOrder($agent_id,0,$card_no,$card_type,$basic_price,$cost,$money,$card_fee,$total_money,$ip);
                $query = $this->OrderList->insert($order_info);
                if(empty($query))
                {
                    $this->E("添加订单失败");
                }
                $order_no = $order_info["order_no"];
                $wallet_info = [
                    "agent_id"=>$agent_id,
                    "order_no"=>$order_no,
                    "type"=>2,
                    "money"=>-$total_money,
                    "info"=>"代理开卡：".$card_no.",卡内余额:".($basic_price/10000).",卡费:".($card_fee/10000).",运费:".($freight/10000),
                    "ctime"=>NOW_TIME
                ];

                $query = $this->WalletLog->insert($wallet_info);
                if(empty($query))
                {
                    $this->E("流水添加失败");
                }
//                if(!sendQueue("app\job\Orders::order_notify_ext",[$order_no]))
//                {
//                    exception("提交充值订单失败");
//                }
                if(!sendMQQueue("fuel_order_recharge",$order_no))
                {
                    exception("提交充值订单失败");
                }
//                $query=$this->UserList->setAgentRebate($agent_id,0,0, $basic_price*$agent_rebate, $order_no,"代理开卡返佣");
//                if(empty($query))
//                {
//
//                    $this->E("佣金结算错误");
//                }
                Db::commit();
                $this->order_log($order_no,"代理开卡");
            }catch (\Exception $e)
            {
                Db::rollback();
                $this->E($e->getMessage());
            }

            $this->resultdata["error"] = 0;
        }catch (\Exception $e)
        {
            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }

    function ajax_agent_card_list_add()
    {
        try
        {
            $agent_id = input("agent_id",0,"intval");
            $card_list = input("card_list","","trim");
            $card_fee = input("card_fee",0,"intval");
            $freight = input("freight",0,"intval");
            if(empty($agent_id)||empty($card_list))
                $this->E("参数不正确");
            $card_fee = $card_fee*10000;
            $freight = $freight*10000;
            $list = [];
            $card_list = explode("\n",$card_list);
            if(empty($card_list))
                $this->E("参数不正确");
            $card_lists = [];
            foreach ($card_list as $val)
            {
                $val = trim($val);
                if($val)
                {
                    $card_lists[] = $val;
                }
            }
            $cost_discount = floatval($this->config_list["CARD_1_COST_DISCOUNT"]["value"]);
            $balances = 0;
            $CardListInfo = $this->CardList->where(["card_no"=>["in",$card_lists]])->select();
            foreach($CardListInfo as $val)
            {
                if($val["status"] !=0)
                    $this->E("使用中：".$val["card_no"]);
                $list[] = $val;
                $balances += intval($val["balance"]);
            }

            if(count($list) != count($card_lists))
            {
                $this->E("不存在卡号：".json_encode(array_diff($card_lists,$list)));
            }

            $card_fees = count($list)*$card_fee;
            $agent_discount = $this->AgentList->where(["id"=>$agent_id])->value("rebate_discount");
//            $agent_rebate = floatval($this->config_list["AGENT_REBATE"]["value"]);
//            $agent_discount = floatval($this->config_list["AGENT_DISCOUNT"]["value"]);
            $money = $balances*$agent_discount+$card_fees+$freight;
            $ip = $this->request->ip();
            Db::startTrans();
            try{
                $query = $this->AgentList->where(["id"=>$agent_id])->where("(balance+credit)>=".$money)->setDec("balance",$money);
                if(empty($query))
                {
                    $this->E("余额不足");
                }
                $info_list = [];
                $order_info_list = [];
                $wallet_info_list = [];
                foreach ($list as $val)
                {
                    $card_no = $val["card_no"];
                    $card_type = $val["card_type"];
                    $basic_price = intval($val["balance"]);
                    $money = $basic_price*$agent_discount;
                    $cost = $basic_price*$cost_discount/100;
                    $total_money = $money+$card_fee;
                    $info = [
                        "agent_id"=>$agent_id,
                        "card_no"=>$card_no,
                        "card_type"=>$card_type,
                        "card_fee"=>$card_fee,
                        "status"=>1
                    ];
                    $order_info = $this->OrderList->addAgentCardOrder($agent_id,0,$card_no,$card_type,$basic_price,$cost,$money,$card_fee,$total_money,$ip);
                    $order_no = $order_info["order_no"];
                    $wallet_info = [
                        "agent_id"=>$agent_id,
                        "order_no"=>$order_no,
                        "type"=>2,
                        "money"=>-$total_money,
                        "info"=>"代理开卡：".$card_no.",卡内余额:".($basic_price/10000).",卡费:".($card_fee/10000).",运费:".($freight/10000),
                        "ctime"=>NOW_TIME
                    ];
                    $info_list[] = $info;
                    $wallet_info_list[] = $wallet_info;
                    $order_info_list[] = $order_info;
                    $query = $this->CardList->where(["status"=>0,"card_no"=>$val["card_no"]])->update(["status"=>1]);
                    if(empty($query))
                    {
                        $this->E("添加失败:".$val);
                    }

//                    $query=$this->UserList->setAgentRebate($agent_id,0,0, $basic_price*$agent_rebate, $order_no,"代理开卡返佣");
//                    if(empty($query))
//                    {
//
//                        $this->E("佣金结算错误");
//                    }

                    $this->order_log($order_no,"代理开卡");

                }


                $query = $this->OrderList->insertAll($order_info_list);
                if(empty($query))
                {
                    $this->E("添加订单失败");
                }
                $query = $this->UserCardList->insertAll($info_list);
                if(empty($query))
                {
                    $this->E("添加失败");
                }

                $query = $this->WalletLog->insertAll($wallet_info_list);
                if(empty($query))
                {
                    $this->E("流水添加失败");
                }
                Db::commit();
                foreach ($order_info_list as $key=>$val)
                {
//                    if(!sendQueue("app\job\Orders::order_notify_ext",[$val["order_no"]]))
//                    {
//                        exception("提交充值订单失败");
//                    }
                    if(!sendMQQueue("fuel_order_status",$order_no))
                    {
                        exception("提交充值订单状态失败");
                    }
                }
            }catch (\Exception $e)
            {
                Db::rollback();
                $this->E($e->getMessage());
            }

            $this->resultdata["error"] = 0;
        }catch (\Exception $e)
        {
            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }

    function agent_wallet_list()
    {
        try {
            $user_ids = $this->UserList->field("id,real_name,mobile")->select();
            $agent_card_list = $this->CardList->where(["status"=>0])->select();
            $agent_list = $this->AgentList->where(["status"=>0])->select();
            $this->assign("agent_card_list",$agent_card_list);
            $this->assign("user_ids",$user_ids);
            $this->assign("agent_list",$agent_list);
        } catch (DataNotFoundException $e) {
        } catch (ModelNotFoundException $e) {
        } catch (DbException $e) {
        }

        $this->assign("page_title","代理卡列表");
        return $this->fetch();
    }
    function ajax_agent_wallet_list()
    {
        try
        {
            $page = input("page",1,"intval");
            $rows = input("rows",30,"intval");
            $agent_id = input("agent_id",0,"intval");
            $type = input("type",-1,"intval");


            $where = [];

            if(!empty($agent_id))
                $where["a.agent_id"] =$agent_id;
            else
                $where["a.agent_id"] = ["gt",0];
            if(in_array($type,[1,2,3]))
            {
                $where["a.type"] =$type;
            }

            $count = $this->WalletLog->alias("a")
                ->join("f_user_list b","a.from_user_id=b.id","left")
                ->where($where)
                ->count();
            $page_total = ceil($count/$rows);
            $page = $page>$page_total?$page_total:$page;
            $page = $page < 1? 1:$page;
            $order_log = $this->WalletLog->alias("a")
                ->join("f_user_list b","a.from_user_id=b.id","left")
                ->join("f_agent_list al" ,"al.id=a.agent_id","left")
                ->field("a.*,b.real_name,b.mobile,al.agent_name")
                ->where($where)
                ->order("a.ctime desc,a.id desc")
                ->limit(($page-1)*$rows,$rows)
                ->select();
            $this->resultdata["data"] = $order_log;
            $this->resultdata["error"] = 0;
            $this->resultdata["total"] = $count;
            $this->resultdata["page"] = $page;
            $this->resultdata["rows"] = $rows;
        }catch (\Exception $e)
        {

            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }
    function ajax_agent_recharge()
    {
        try
        {

            $id = input("id",0,"intval");
            $amount = input("amount",-1,"intval");
            if(empty($id)||empty($amount))
                $this->E("参数不正确");
            if(($amount%100)>0)
                exception("amount is error",102);
            $user_card_info = $this->UserCardList->where(["id" =>$id,"status"=>1])->find();
            if(empty($user_card_info))
                exception("卡不存在",102);

            $user_id = $user_card_info["user_id"];
            $agent_id = $user_card_info["agent_id"];
            $card_no = $user_card_info["card_no"];
            $card_type = $user_card_info["card_type"];
            $agent_info = $this->AgentList->where(["id"=>$agent_id])->find();
            if(empty($agent_info))
                exception("代理信息不存在",102);
            $money_discount = $agent_info["money_discount"];

            $freight = 0;
            $card_fee = 0;
            $discount_money = 0;
            $basic_price    = $amount*10000;
            $cost           = $amount*9500;
            $money          = $amount*10000*$money_discount;
            $mode           = 0;

            $total_money = $money+$freight+$card_fee-$discount_money;

            $order_no       = get_order_no("D",$card_no);
            $info = [
                "order_no"      => $order_no,
                "user_id"       => $user_id,
                "agent_id"      => $agent_id,
                "card_no"       => $card_no,
                "card_type"     => $card_type,
                "basic_price"   => $basic_price,
                "cost"          => $cost,
                "money"         => $money,
                "freight"       => $freight,
                "card_fee"      => $card_fee,
                "discount_money"=> $discount_money,
                "total_money"   => $total_money,
                "mode"          => $mode,
                "pay_type"      => 4,
                "pay_status"    => 1,
                "ctime"         => NOW_TIME,
                "mtime"         => NOW_TIME,
                "ip"            => $this->request->ip(),
                "token_type"    => 0,
            ];
            Db::startTrans();
            try{
                $query = $this->AgentList->where(["id"=>$agent_id])->where("(balance+credit)>=".$total_money)->setDec("balance",$total_money);
                if(empty($query))
                    exception("余额不足",102);
                $query = $this->OrderList->insert($info);
                if(empty($query))
                    exception("添加订单失败",102);
                $wallet_info = [
                    "agent_id"=>$agent_id,
                    "order_no"=>$order_no,
                    "type"=>2,
                    "money"=>-$total_money,
                    "info"=>"代理充值：".$card_no,
                    "ctime"=>NOW_TIME
                ];
                $query = $this->WalletLog->insert($wallet_info);
                if(empty($query))
                {
                    exception("流水添加失败");
                }

                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                exception($e->getMessage(),$e->getCode());
            }
//            if(!sendQueue("app\job\Orders::order_recharge",[$order_no]))
//            {
//                exception("提交充值订单失败");
//            }
            if(!sendMQQueue("fuel_order_recharge",$order_no))
            {
                exception("提交充值订单失败");
            }
            $this->resultdata["error"] = 0;

        }catch (\Exception $e)
        {

            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }
}